package xyz.labradormm.spider.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.transfer.TransferManager;
import com.qcloud.cos.transfer.TransferManagerConfiguration;
import com.qcloud.cos.transfer.Upload;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import xyz.labradormm.spider.service.IUploadService;

import java.io.ByteArrayInputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author hhj
 * @description
 * @date 2023-12-05 11:24
 * @menu
 */
@Component
@Qualifier("TencentUploadService")
@Slf4j
public class TencentUploadServiceImpl implements IUploadService {


    @Value("${mmspider.tencent.cos.bucketName:}")
    private String bucketName;

    @Value("${mmspider.tencent.cos.domain:}")
    private String domain = "https://mm-res-1317369731.cos.ap-guangzhou.myqcloud.com/";

    @Autowired
    private TransferManager transferManager;

    @Autowired
    private COSClient cosClient;

    @Override
    public String uploadImg(byte[] uploadBytes, String fileName) {
        return baseUploadFile(uploadBytes, fileName, "images");
    }

    @Override
    public String createDefaultKey() {
        return System.currentTimeMillis() + RandomUtil.randomString(10);
    }

    @Override
    public String uploadVideo(byte[] uploadBytes, String fileName) {
        return baseUploadFile(uploadBytes, fileName, "videos");
    }

    public String baseUploadFile(byte[] uploadBytes, String fileName, String folder) {
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(uploadBytes);) {
            if (StringUtils.isEmpty(fileName)) {
                fileName = createDefaultKey();
                if ("images".equals(folder)) {
                    fileName += ".jpg";
                } else if ("videos".equals(folder)) {
                    fileName += ".mp4";
                }
            }
            String key = String.format("%s/%s", folder, fileName);
            ObjectMetadata objectMetadata = new ObjectMetadata();
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, byteArrayInputStream, objectMetadata);
            if ("temps".equals(folder)) {
                putObjectRequest.setStorageClass(StorageClass.Standard_IA);
            }
            // 高级接口会返回一个异步结果Upload
            // 可同步地调用 waitForUploadResult 方法等待上传完成，成功返回 UploadResult, 失败抛出异常
            Upload upload = transferManager.upload(putObjectRequest);
            UploadResult uploadResult = upload.waitForUploadResult();
            return domain.concat(key);
        } catch (Exception e) {
            log.error("上传文件异常", e);
        }
        return null;
    }

    @Override
    public String uploadTemp(byte[] uploadBytes, String fileName) {
        return baseUploadFile(uploadBytes, fileName, "temps");
    }

    @Override
    public void deleteFile(String resourceUrl) {

    }

    @Override
    public String uploadBigFile(byte[] uploadBytes, String fileName) {
        try {
            if (StringUtils.isEmpty(fileName)) {
                fileName = createDefaultKey();
            }
            String key = "bigfile/".concat(fileName);
            InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(bucketName, key);
            // 分块上传的过程中，仅能通过初始化分块指定文件上传之后的 metadata
            // 需要的头部可以在这里指定
            ObjectMetadata objectMetadata = new ObjectMetadata();
            request.setObjectMetadata(objectMetadata);
            InitiateMultipartUploadResult initResult = cosClient.initiateMultipartUpload(request);
            // 获取 uploadid
            String uploadId = initResult.getUploadId();
            log.info("uploadId=" + uploadId);
            return domain.concat(key);
        } catch (Exception e) {
            log.error("上传大文件异常", e);
        }
        return null;
    }


}
